<template>
  <div class="patrol-route-add">
    <div class="form-header">
      <i class="el-icon-plus"></i> 添加巡更路线
      <span class="back-link" @click="goBack()">* 返回列表</span>
    </div>

    <div class="form-container">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="120px"
        class="patrol-form"
      >
        <el-form-item label="所属小区" prop="communityId" required>
          <el-select
            v-model="form.communityId"
            placeholder="请选择小区"
            style="width: 100%"
            @change="handleCommunityChange"
          >
            <el-option
              v-for="item in communityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="巡更路线名" prop="routeName" required>
          <el-input
            v-model="form.routeName"
            placeholder="请输入巡更路线名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="巡更点选择" prop="patrolPoints" required>
          <div class="patrol-points-container">
            <div class="points-col">
              <div class="point-col-header">
                <el-checkbox v-model="leftCheckedAll">未选列表</el-checkbox>
                <span class="count">{{pointsLeft.length}}</span>
              </div>
              <div class="points-list">
                <div v-for="point in pointsLeft" :key="point.id" class="point-item">
                  <el-checkbox v-model="point.checked">{{point.name}}</el-checkbox>
                </div>
              </div>
            </div>
            
            <div class="transfer-actions">
              <el-button 
                size="small" 
                type="primary" 
                icon="el-icon-arrow-right" 
                plain 
                @click="moveToRight"
              ></el-button>
              <el-button 
                size="small" 
                type="primary" 
                icon="el-icon-arrow-left" 
                plain 
                @click="moveToLeft"
              ></el-button>
            </div>
            
            <div class="points-col">
              <div class="point-col-header">
                <el-checkbox v-model="rightCheckedAll">已选列表</el-checkbox>
                <span class="count">{{pointsRight.length}}</span>
              </div>
              <div class="points-list">
                <div v-for="point in pointsRight" :key="point.id" class="point-item">
                  <el-checkbox v-model="point.checked">{{point.name}}</el-checkbox>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="巡更时间" required>
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-time-select
                v-model="form.startTime"
                placeholder="开始时间"
                style="width: 100%"
                :picker-options="{
                  start: '00:00',
                  step: '00:30',
                  end: '23:30'
                }">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align: center">
            <span>至</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-time-select
                v-model="form.endTime"
                placeholder="结束时间"
                style="width: 100%"
                :picker-options="{
                  start: '00:00',
                  step: '00:30',
                  end: '23:30',
                  minTime: form.startTime
                }">
              </el-time-select>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入分类描述"
            class="compact-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="拍照要求" prop="photoRequired">
          <el-radio-group v-model="form.photoRequired">
            <el-radio :label="1">要求拍照</el-radio>
            <el-radio :label="0">无要求</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <div class="form-actions">
          <el-button type="primary" @click="submitForm('form')">
            <i class="el-icon-check"></i> 保存
          </el-button>
          <el-button @click="cancelForm">取消</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        communityId: "",
        routeName: "",
        patrolPoints: [],
        startTime: "",
        endTime: "",
        photoRequired: 1,
        status: 1,
        remark: "",
      },
      rules: {
        communityId: [
          { required: true, message: "请选择所属小区", trigger: "change" },
        ],
        routeName: [
          { required: true, message: "请输入巡更路线名称", trigger: "blur" },
        ],
        patrolPoints: [
          { required: true, message: "请选择巡更点", trigger: "change" },
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "change" }
        ]
      },
      // 下拉框选项
      communityOptions: [],
      // 巡更点列表数据
      pointsLeft: [],
      pointsRight: [],
      leftCheckedAll: false,
      rightCheckedAll: false,
      loading: {
        community: false,
        patrolPoints: false,
      }
    };
  },

  created() {
    // 页面加载时获取小区数据
    this.fetchCommunityData();
  },
  
  watch: {
    pointsLeft: {
      handler(val) {
        if (val.length > 0) {
          this.leftCheckedAll = val.every(item => item.checked);
        } else {
          this.leftCheckedAll = false;
        }
      },
      deep: true
    },
    pointsRight: {
      handler(val) {
        if (val.length > 0) {
          this.rightCheckedAll = val.every(item => item.checked);
        } else {
          this.rightCheckedAll = false;
        }
        
        // 简化处理，直接更新表单数据
        this.form.patrolPoints = val.map(item => item.id).filter(id => id !== null && id !== undefined);
        console.log("监听更新patrolPoints:", this.form.patrolPoints);
      },
      deep: true
    },
    leftCheckedAll(val) {
      this.pointsLeft.forEach(item => {
        item.checked = val;
      });
    },
    rightCheckedAll(val) {
      this.pointsRight.forEach(item => {
        item.checked = val;
      });
    },
    "form.communityId": function(val) {
      if (val) {
        this.fetchPatrolPointData(val);
      }
    }
  },

  methods: {
    // 返回列表页
    goBack() {
      this.$router.go(-1);
    },
    
    // 获取小区数据
    fetchCommunityData() {
      this.loading.community = true;
      this.$axios.get('api/infrastructure-server/community/queryAll')
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.communityOptions = response.data.data.map(item => {
              return { value: item.id, label: item.name };
            });
          } else {
            this.$message.error(response.data.message || "获取社区列表失败");
          }
        })
        .catch(error => {
          console.error('获取社区列表错误:', error);
          this.$message.error("获取社区列表错误");
        })
        .finally(() => {
          this.loading.community = false;
        });
    },

    // 获取巡更点数据
    fetchPatrolPointData(communityId) {
      if (!communityId) return;

      this.loading.patrolPoints = true;
      this.form.patrolPoints = [];
      this.pointsLeft = [];
      this.pointsRight = [];

      this.$axios.get(`api/patrol-server/patrol/queryByCommunityId/${communityId}`)
        .then(response => {
          if (response.data && response.data.code === 200) {
            // 初始化左侧列表数据
            this.pointsLeft = response.data.data.map(item => {
              return {
                id: item.pointId,
                name: item.pointName,
                checked: false
              };
            });
            console.log("巡更点数据:", this.pointsLeft);
          } else {
            this.$message.error(response.data.message || "获取巡更点列表失败");
          }
        })
        .catch(error => {
          console.error('获取巡更点列表错误:', error);
          this.$message.error("获取巡更点列表错误");
        })
        .finally(() => {
          this.loading.patrolPoints = false;
        });
    },

    // 小区变更时触发
    handleCommunityChange(value) {
      this.fetchPatrolPointData(value);
    },
    
    // 将选中的项移动到右侧
    moveToRight() {
      const selected = this.pointsLeft.filter(item => item.checked);
      if (selected.length === 0) {
        this.$message.warning("请先选择要添加的巡更点");
        return;
      }
      
      // 将选中的点移到右侧 - 简化逻辑，确保显示
      selected.forEach(point => {
        // 确保id不为null
        if (point.id !== null && point.id !== undefined) {
          this.pointsRight.push({
            id: point.id,
            name: point.name,
            checked: false
          });
        }
      });
      
      // 从左侧移除选中的点
      this.pointsLeft = this.pointsLeft.filter(item => !item.checked);
      
      // 手动更新patrolPoints，直接使用完整的ID集合
      this.form.patrolPoints = this.pointsRight.map(item => item.id).filter(id => id !== null && id !== undefined);
      console.log("更新后的patrolPoints:", this.form.patrolPoints);
    },
    
    // 将选中的项移动到左侧
    moveToLeft() {
      const selected = this.pointsRight.filter(item => item.checked);
      if (selected.length === 0) {
        this.$message.warning("请先选择要移除的巡更点");
        return;
      }
      
      // 将选中的点移到左侧
      selected.forEach(point => {
        // 确保id不为null
        if (point.id !== null && point.id !== undefined) {
          this.pointsLeft.push({
            id: point.id,
            name: point.name,
            checked: false
          });
        }
      });
      
      // 从右侧移除选中的点
      this.pointsRight = this.pointsRight.filter(item => !item.checked);
      
      // 手动更新patrolPoints，直接使用完整的ID集合
      this.form.patrolPoints = this.pointsRight.map(item => item.id).filter(id => id !== null && id !== undefined);
      console.log("更新后的patrolPoints:", this.form.patrolPoints);
    },

    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 表单验证通过
          this.savePatrolRoute();
        } else {
          // 表单验证不通过
          this.$message.error("请完善表单信息");
          return false;
        }
      });
    },

    // 保存巡更路线
    savePatrolRoute() {
      // 最后处理空数组的情况
      if (!this.form.patrolPoints || this.form.patrolPoints.length === 0) {
        this.form.patrolPoints = [];
      } else {
        // 最后一次过滤确保没有null值
        this.form.patrolPoints = this.form.patrolPoints.filter(id => id !== null && id !== undefined);
      }
      
      // 准备提交的数据
      const submitData = {
        ...this.form
      };
      
      console.log("提交的数据:", submitData);
      
      this.$axios
        .post("api/patrol-server/patrolRoute/add", submitData)
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.$message.success("保存成功");
            this.goBack();
          } else if (response.data.code === 400 && response.data.message.includes("已存在")) {
            this.$message.error("巡更路线名称已存在");
          } else {
            this.$message.error(response.data.message || "保存失败");
          }
        })
        .catch(error => {
          console.error("保存巡更路线出错:", error);
          this.$message.error("保存巡更路线出错");
        });
    },

    // 取消按钮
    cancelForm() {
      this.$refs.form.resetFields();
    }
  }
};
</script>

<style scoped>
.patrol-route-add {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-header {
  font-size: 18px;
  font-weight: bold;
  padding-bottom: 20px;
  border-bottom: 2px solid #ebeef5;
  margin-bottom: 30px;
  color: #409EFF;
}

.back-link {
  color: #409eff;
  font-size: 14px;
  float: right;
  cursor: pointer;
  transition: all 0.3s;
}

.back-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.form-container {
  max-width: 650px;
  margin: 0 auto;
}

.patrol-points-container {
  display: flex;
  min-height: 300px;
  border: 1px solid #ebeef5;
}

.points-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f9f9f9;
}

.point-col-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.count {
  font-size: 12px;
  color: #909399;
}

.points-list {
  flex: 1;
  overflow-y: auto;
}

.point-item {
  padding: 8px 15px;
}

.point-item:hover {
  background-color: #f5f7fa;
}

.transfer-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 0 15px;
}

.transfer-actions .el-button {
  margin: 5px 0;
}

.form-actions {
  margin-top: 40px;
  text-align: center;
  padding-top: 30px;
  border-top: 1px dashed #ebeef5;
}

.form-actions .el-button {
  padding: 10px 22px;
  min-width: 100px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

.compact-input textarea {
  resize: none;
  height: 80px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-form-item__label {
  font-weight: 500;
}

.el-radio + .el-radio {
  margin-left: 30px;
}

.el-input__inner,
.el-textarea__inner {
  border-radius: 4px;
  border-color: #dcdfe6;
  padding: 0 12px;
  height: 36px;
}

.el-textarea__inner {
  padding: 8px 12px;
  height: auto;
}

.el-form-item.is-required .el-form-item__label:before {
  color: #f56c6c;
}
</style>